package com.cn.ccp.action.course.quality;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseContentBean;
import com.cn.ccp.bean.CourseContentManageBean;
import com.cn.ccp.bean.CourseEvaluationBean;
import com.cn.ccp.bean.CourseOutlineBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.StudentMarkedHistoryBean;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;

/**
 * 课程精品课程评选
 * @author renyongcheng
 *
 */
public class CourseQualityAction extends BaseAction {
	private Logger log = Logger.getLogger(CourseQualityAction.class);
	private List<CourseBean> courseList ;
	private CourseBean course ;
	private List<CourseContentManageBean> courseChapterList ;
	private List<StudentMarkedHistoryBean> markedList;//学生评价历史
	private String courseId,strNextCourseDetailId,strProCourseDetailId;
	private String outline;//课程大纲
	private String courseEva;//课程考核办法
	
	private boolean showEditOutline ,showEditEvaluation ;
	private String[] arrayId;// 课程详细信息id数组
	private int curIndex = -1;//当前课程详细信息索引
	
	public CourseQualityAction(){
		log.info("-------CourseQualityAction()-------");
	}
 
	private void resetOutlineAndEvlaSession(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.removeAttribute(CCPContants.OUTLINE_FILE_PATH);
		session.removeAttribute(CCPContants.EVALUA_FILE_PATH);
		session.removeAttribute(CCPContants.FILE_TYPE);
		showEditEvaluation = true;
		showEditOutline = true;
		curIndex = -1;
	}
	
	public String showQualityDetail(){
		resetOutlineAndEvlaSession();
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		courseId = varMap.get("id");
		if(courseId != null)
			course = this.getSelectCourseService().getCouseDetailById(courseId);
		if(course.getImage().equals("book-default.png")){
			
		}else{
			File sourseFile = null;
			if(course.getFile_path_id() !=  -1)
				sourseFile = new File(getFilePathService().findFilePathById(course.getFile_path_id()).getPath()+course.getImage());
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + course.getImage());
			
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId() + File.separator);
			if(des.mkdir()){
				des.mkdirs();
			}
			des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId()  + File.separator +sourseFile.getName());
			CCPContants.copyFile(sourseFile.getPath(), des.getPath());
			course.setImage(CCPContants.getCurrUserId()+"/"+des.getName());
		}
		log.info(course.getImage());
		
		CourseOutlineBean courseOutLineBean = getCourseService().getOutlineByCourseId(courseId);
		if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null && courseOutLineBean.getOutline().endsWith(".txt")){
			showEditOutline = true;
		}else if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null){//其他文件，使用组件显示
			showEditOutline = false; 
			String savePath = getOutlineFilePath();
			savePath += courseOutLineBean.getOutline();
			String outlinePath  = CCPContants.copyOutline(savePath, courseOutLineBean.getOutline(),Contants.OUTLINE_DERECT);
			log.info("------------outlinePath = "+outlinePath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.OUTLINE_FILE_PATH, courseOutLineBean.getOutline());
		}
		log.info(courseOutLineBean);
		CourseEvaluationBean assessmentBean = getCourseService().getEvaluationByCourseId(courseId);
		if(assessmentBean != null && assessmentBean.getContents() != null && assessmentBean.getContents().endsWith(".txt"))
			showEditEvaluation = true;
		else if(assessmentBean != null && assessmentBean.getContents() != null){
			showEditEvaluation = false ;
			String savePath = getOutlineFilePath();
			savePath += assessmentBean.getContents();
			String evaluPath  = CCPContants.copyOutline(savePath, assessmentBean.getContents(),Contants.EVALUATION_DERECT);
			log.info("------------evaluPath = "+evaluPath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.EVALUA_FILE_PATH, assessmentBean.getContents());
		}
		return UPDATE;
	}
 	
	/**
	 * 精品课程
	 * @return
	 */
	public String doQuality(){
		log.info("----------- courseId = "+courseId);
		getCourseService().doQuality(true,courseId);
		return MAIN;
	}
	
	
	/**
	 * 精品课程
	 * @return
	 */
	public String cancelQuality(){
		log.info("----------- courseId = "+courseId);
		getCourseService().doQuality(false,courseId);
		return MAIN;
	}
	
	public String backFromContents(){
		curIndex = -1;
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		courseId = varMap.get("courseId");
		log.info("----------- courseId = "+courseId);
		if(courseId != null)
			course = this.getSelectCourseService().getCouseDetailById(courseId);
		if(course.getImage()  != null && !"".equalsIgnoreCase(course.getImage().trim())){
			File sourseFile = null;
			if(course.getFile_path_id() !=  -1)
				sourseFile = new File(getFilePathService().findFilePathById(course.getFile_path_id()).getPath()+course.getImage());
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + course.getImage());
			
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId() + File.separator);
			if(des.mkdir()){
				des.mkdirs();
			}
			des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId()  + File.separator +sourseFile.getName());
			CCPContants.copyFile(sourseFile.getPath(), des.getPath());
			course.setImage(CCPContants.getCurrUserId()+"/"+des.getName());
//			course.setImage(CCPContants.getCurrUserId()+"/"+file.getName());
		}
		log.info(course.getImage());
		return MAIN;
	}
	
	
	@Override
	public void getpagedetail() {
		setItemCount(getCourseService().getCountQuality());
		int currentpage = getCurrentPage();
		int pagesize = getPageSize();
		int start = (currentpage - 1) * pagesize;
		courseList = getCourseService().pageQueryForQuality(start, pagesize);
	}
 
	 

	public List<CourseBean> getCourseList() {
			getpagedetail();
		return courseList;
	}

	public void setCourseList(List<CourseBean> courseList) {
		this.courseList = courseList;
	}

 

	public CourseBean getCourse() {
		if(course == null){
			course = new CourseBean();
		}
		return course;
	}

	public void setCourse(CourseBean course) {
		this.course = course;
	}

	public String showCourseContent(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String chapterId = varMap.get("chapterId");
		
		String curI = varMap.get("curIndex");
		if(curI != null ){
			this.curIndex = Integer.parseInt(curI) ;
			strNextCourseDetailId = varMap.get("strNextCourseDetailId");
			strProCourseDetailId = varMap.get("strProCourseDetailId");
			
		}
		
		log.info("----------- chapterId = "+chapterId);
		log.info("----------- courseId = "+courseId);
		CourseContentBean courseContentBean = getCourseContentService().showBean(chapterId);
		int index =  courseContentBean.getSection_file_url().lastIndexOf(".");
		String fileType = courseContentBean.getSection_file_url().substring(index+1,courseContentBean.getSection_file_url().length());
		String title = "【"+courseContentBean.getCourse_name()+"-"+courseContentBean.getChapter_title()+"-"+courseContentBean.getSection_file_name()+"】";
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		
		String path = null;
		if("zip".equalsIgnoreCase(fileType)){
			path = "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".htm";
			File uFile = new File(System.getProperty("webapp.root") + "tempfile"+path);
			if(uFile.exists())
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, path);
			else
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".html");
		}else {
			path = 	CCPContants.getFilePath(courseContentBean.getSection_file_url() , getFilePathService(),courseContentBean.getFilePathId(),CCPContants.getUserBean().getId());
			String filePath = CCPContants.getCurrUserId()+"/"+(new File(path)).getName();
			log.info("---------filePath = "+filePath);
			session.setAttribute(CCPContants.VIDEO_FILE_NAME, filePath);
		}
		log.info("---------path = "+path);
		
		
		if(title.length() > 30)
			title  = title.substring(0, 30) + "...";
		session.setAttribute(CCPContants.COURSE_NAME, title);
		
		log.info("-----------fileType = "+fileType);
		session.setAttribute(CCPContants.FILE_TYPE, fileType);
		 
		int len = arrayId.length;
		for(int i=0 ; i<len; i++){
			if(chapterId.equalsIgnoreCase(arrayId[i])){
				curIndex = i;
				break;
			}
		}
		if(fileType.equalsIgnoreCase("swf") && courseContentBean.getSection_file_type().equalsIgnoreCase("swf"))
			return DEFAULT_SWF_URL;
		
		
		if(fileType.equalsIgnoreCase("swf") || fileType.equalsIgnoreCase("pdf"))
			return SWF_FILE;
		else{
			
			if("flv".equalsIgnoreCase(fileType))
				return FLV_URL;
			
			if(CCPContants.DEFAULT_VEDIO_FILE_TYPE.indexOf(fileType) >= 0){
				if("ogv".equalsIgnoreCase(fileType))
					fileType = "ogg";
				session.setAttribute(CCPContants.VIDEO_FILE_TYPE, fileType);
				log.info("---------default vedio file-------");
				return DEFAULT_VEDIO_FILE;
			}else
				return VEDIO_FILE;
		}
	}
	
	
	public List<CourseContentManageBean> getCourseChapterList() {
		/*if(course == null)
			return null;
		if(course.getId() != null && !course.getId().equals("")){
			List<CourseContentBean> ccList = getCourseContentService().getCourseContentList(course.getId());
			int len = ccList.size();
			arrayId =  new String[len];
			courseChapterList = new ArrayList<CourseContentManageBean>();
			String cNumber = "";
			CourseContentManageBean ccmb = null ;
			for (int i = 0; i < ccList.size(); i++) {
				CourseContentBean ccb = ccList.get(i);
				arrayId[i] = String.valueOf(ccb.getId());
				if(!cNumber.equals("") && !cNumber.equals(ccb.getChapter_number()))
					courseChapterList.add(ccmb);
				if(cNumber.equals("")){
					ccmb = new CourseContentManageBean(); 
					ccmb.setChapter_number(ccb.getChapter_number());
					ccmb.setTitle1(ccb.getChapter_title(), i ,ccb.getChapter_number());
					ccmb.setTitle2(i);
				}else if(!ccmb.getChapter_number().equals(ccb.getChapter_number())){
					ccmb = new CourseContentManageBean(); 
					ccmb.setChapter_number(ccb.getChapter_number());
					ccmb.setTitle1(ccb.getChapter_title(), i,ccb.getChapter_number());
					ccmb.setTitle2(i);
				}
				ccmb.getCcbList().add(ccb);
				
				cNumber = ccb.getChapter_number() ;
			}
			if(ccmb != null)
				courseChapterList.add(ccmb);
		}
		if(courseChapterList == null)
			courseChapterList = new ArrayList<CourseContentManageBean>();
		return courseChapterList;*/
		
		List<String> tmpList = new ArrayList<String>();
		List<CourseContentBean> zList = getCourseContentService().getCourseContentList(courseId);
		courseChapterList = new ArrayList<CourseContentManageBean>();
		CourseContentManageBean firstLevelBean = null;//章节bean
		CourseContentManageBean secondLevelBean = null;//小节节bean
		String secondTitle = "";
		for(CourseContentBean b : zList){
			if(b.getSection_file_name() != null && !"".equalsIgnoreCase(b.getSection_file_name()))
				tmpList.add(""+b.getId());
				
			if(firstLevelBean == null){
				firstLevelBean =  addFirstLevel(b,courseChapterList,false);
			}else{
				if(b.getChapter_number().equalsIgnoreCase(firstLevelBean.getChapter_number())){//一个章节的内容
					if("0".equalsIgnoreCase(b.getStatus())){//章节下面的课程内容
						firstLevelBean.getCcList().add(b);
					}else{
						if(secondLevelBean == null){//小节bean为空
							secondLevelBean = addSecondLevel(b,false);
							firstLevelBean.getXjMList().add(secondLevelBean);
							secondTitle = b.getChapter_title();
							continue;
						}
						
						if(secondTitle.equals(b.getChapter_title())){//同一小节的课程内容
							secondLevelBean.getCcmList().add(b);
						}else{//不是一个小节的内容，则创建新的小节
							secondLevelBean = addSecondLevel(b,false);
							firstLevelBean.getXjMList().add(secondLevelBean);
							secondTitle = b.getChapter_title();
						}
						
					}
					
				}else{//不是一个章节的内容，添加一个新的章节目录
					firstLevelBean =  addFirstLevel(b,courseChapterList,false);
					secondLevelBean = null;
				}
				
			}
		}
		
		arrayId = new String[tmpList.size()];
		for (int i = 0; i < tmpList.size(); i++) {
			arrayId[i] = tmpList.get(i);
		}
		
		
		if(courseChapterList == null)
			courseChapterList = new ArrayList<CourseContentManageBean>();
		return courseChapterList;
	}

	public void setCourseChapterList(List<CourseContentManageBean> courseChapterList) {
		this.courseChapterList = courseChapterList;
	}

	public List<StudentMarkedHistoryBean> getMarkedList() {
		log.info("------------courseId = "+courseId);
		if(courseId != null)
			markedList =  getSelectCourseService().getMarkedList(courseId);
		return markedList;
	}

	public void setMarkedList(List<StudentMarkedHistoryBean> markedList) {
		this.markedList = markedList;
	}

	public String getCourseId() {
		return courseId;
	}

	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}

	public String getOutline() {
		if(courseId != null){
			Object obj = getCourseService().getOutlineByCourseId(courseId);
			if(obj != null){
				CourseOutlineBean b = (CourseOutlineBean)obj; 
				
				if(b.getOutline().toUpperCase().endsWith(".TXT")){
					String savePath = getOutlineFilePath();
					savePath += b.getOutline();
					log.info(savePath);
					BufferedReader reader = null;
					StringBuffer buf = new StringBuffer();
					try {
						reader = new BufferedReader(new FileReader(savePath));
						String text = null;
						while ((text = reader.readLine()) != null){
							buf.append(text);
							buf.append(System.getProperty("line.separator"));
						}
						outline = buf.toString();
					} catch (IOException e) {
						log.info("read outline failed : ",e);
					} finally{
						try {
							if(reader != null)
								reader.close();
						} catch (IOException e) {
						}
					} 
				}
			}
		}
		return outline;
	}

	public void setOutline(String outline) {
		this.outline = outline;
	}
	private String getOutlineFilePath(){
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files";
		if(path != null){
			savePath = path.getPath();
		}
		return savePath;
	}
	public String getCourseEva() {
		courseEva = null; 
		CourseEvaluationBean assessmentBean = null;
		if(courseId != null)
			assessmentBean = getCourseService().getEvaluationByCourseId(courseId);
		if(assessmentBean != null){
				
			if(assessmentBean.getContents().toUpperCase().endsWith(".TXT")){
				String savePath = getOutlineFilePath();
				savePath += assessmentBean.getContents();
				log.info(savePath);
				BufferedReader reader = null;
				StringBuffer buf = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						buf.append(text);
						buf.append(System.getProperty("line.separator"));
					}
					courseEva = buf.toString();
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				} 
			}
		}
		return courseEva;
	}

	public void setCourseEva(String courseEva) {
		this.courseEva = courseEva;
	}

	public boolean isShowEditOutline() {
		return showEditOutline;
	}

	public void setShowEditOutline(boolean showEditOutline) {
		this.showEditOutline = showEditOutline;
	}

	public boolean isShowEditEvaluation() {
		return showEditEvaluation;
	}

	public void setShowEditEvaluation(boolean showEditEvaluation) {
		this.showEditEvaluation = showEditEvaluation;
	}
 
	public String getStrNextCourseDetailId() {
		if(arrayId == null){
			List<CourseContentBean> ccList = getCourseContentService().getCourseContentList(courseId);
			int len = ccList.size();
			arrayId =  new String[len];
			for (int i = 0; i < ccList.size(); i++) {
				CourseContentBean ccb = ccList.get(i);
				arrayId[i] = String.valueOf(ccb.getId());
			}
		}
		if(curIndex + 1 < arrayId.length)
			strNextCourseDetailId = arrayId[curIndex +1 ];
		else
			strNextCourseDetailId = "-1";
		return strNextCourseDetailId;
	}

	public void setStrNextCourseDetailId(String strNextCourseDetailId) {
		this.strNextCourseDetailId = strNextCourseDetailId;
	}

	public String getStrProCourseDetailId() {
		if(arrayId == null){
			List<CourseContentBean> ccList = getCourseContentService().getCourseContentList(courseId);
			int len = ccList.size();
			arrayId =  new String[len];
			for (int i = 0; i < ccList.size(); i++) {
				CourseContentBean ccb = ccList.get(i);
				arrayId[i] = String.valueOf(ccb.getId());
			}
		}
		if(curIndex - 1 >= 0)
			strProCourseDetailId = arrayId[curIndex - 1 ];
		else
			strProCourseDetailId = "-1";
		return strProCourseDetailId;
	}

	public void setStrProCourseDetailId(String strProCourseDetailId) {
		this.strProCourseDetailId = strProCourseDetailId;
	}

	public int getCurIndex() {
		return curIndex;
	}

	public void setCurIndex(int curIndex) {
		this.curIndex = curIndex;
	}

}
